package com.myjoje.config.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Configuration
public class ShiroConfig {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private String redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;

    /**
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        //设置SecurityManager
        filterFactoryBean.setSecurityManager(securityManager);

        //设置登录url
        filterFactoryBean.setLoginUrl("/pub/need_login");

        //登录成功的url
        //filterFactoryBean.setSuccessUrl("/home/home_index");

        //无权限url
        filterFactoryBean.setUnauthorizedUrl("/pub/not_permit");

        //添加自定义过滤器
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        filterMap.put("rolesOr", new RolesOrAuthorizationFilter());
        filterFactoryBean.setFilters(filterMap);

        //此处需使用LinkedHashMap
        Map<String, String> filterChainMap = new LinkedHashMap<>();
        //退出过滤器
        filterChainMap.put("/logout", "logout");
        //匿名过滤器
        filterChainMap.put("/pub/**", "anon");
        filterChainMap.put("/static/**", "anon");
        //管理员角色才可以访问
        //filterChainDefinitionMap.put("/system/**", "rolesOr[root,admin]");
        //有更新权限才可以访问
        //filterChainDefinitionMap.put("/dict/update", "perms[dict_update]");

        //其他的都是登录后可以访问
        filterChainMap.put("/**", "authc");

        filterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
        return filterFactoryBean;
    }

    /**
     * 安全管理器，需设置SessionManager,CacheManager,Realm
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager());
        //使用自定义的CacheManager
//        securityManager.setCacheManager(redisCacheManager());
        //realm放到最后
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    /**
     * 自定义realm,需设置密码加密
     */
    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm = new CustomRealm();
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }

    /**
     * 密码加密
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1);
        return credentialsMatcher;
    }


    /**
     * 自定义SessionManager，需设置SessionDao
     */
    @Bean
    public SessionManager sessionManager() {
        CustomSessionManager sessionManager = new CustomSessionManager();
        //使用redisSessionDao
//        sessionManager.setSessionDAO(redisSessionDAO());
        sessionManager.setGlobalSessionTimeout(60 * 60 * 1000);
        return sessionManager;
    }


    /**
     * 配置Redis
     */
    @Bean
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(redisHost + ":" + redisPort);
        redisManager.setPassword(redisPassword);
        return redisManager;
    }

    /**
     * redis缓存管理器, 需设置RedisManager
     *
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //设置缓存过期时间
        redisCacheManager.setExpire(30 * 60);
        return redisCacheManager;
    }

    /**
     * Session持久化，需设置RedisManager，SessionIdGenerator
     *
     * @return
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        redisSessionDAO.setSessionIdGenerator(session ->
                UUID.randomUUID().toString().replace("-", ""));
        return redisSessionDAO;
    }

    //此Bean可以不配置，ShiroBeanConfiguration中已经配置过
//    @Bean
//    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
//        return new LifecycleBeanPostProcessor();
//    }

    /**
     * 启用shiro注解
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 解决spring aop和注解配置一起使用的bug
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }
}
